package com.koron.css2.baseConfig.impl;


import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.WaterPriceBean;
import com.koron.css2.baseConfig.bean.WaterPriceDetailBean;
import com.koron.css2.baseConfig.bean.WaterPriceLadderBean;
import com.koron.css2.baseConfig.mapper.WaterPriceMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import com.koron.util.ValidationKey;
import com.mysql.cj.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;
/**
 * 用水价格-编辑
 * @author 李攀
 *
 */
public class WaterPriceUpdate implements ServerInterface {

	private static Logger logger = LogManager.getLogger(WaterPriceUpdate.class);

	@Override
	@ValidationKey(clazz = WaterPriceBean.class,method = "insert")
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			WaterPriceMapper mapper = factory.getMapper(WaterPriceMapper.class);
			WaterPriceBean bean = JsonUtils.objectToPojo(req.getData(), WaterPriceBean.class);
			if (StringUtils.isNullOrEmpty(bean.getId())) {
				return MessageBean.create(Constant.ILLEGAL_PARAMETER, "id为空", void.class);
			}
			bean.setUpdateInfo(userInfo);
			
			MessageBean<?> retMsg = WaterPriceAdd.check(userInfo, bean);
			if(retMsg.getCode() != Constant.MESSAGE_INT_SUCCESS) {
				return retMsg;
			}

			mapper.deleteWaterPriceLadderByPriceId(bean.getId());
			mapper.deleteWaterPriceDetailByPriceId(bean.getId());
			mapper.updateWaterPrice(bean);
			for (WaterPriceDetailBean detailBean : bean.getDetails()) {
				if (org.apache.commons.lang3.StringUtils.isNotBlank(detailBean.getPenaltyStrategyId()) || detailBean.getFixedMoney() > 0 || detailBean.getFixedPrice() > 0 || detailBean.getLadders().size() > 0) {
					mapper.insertWaterPriceDetail(detailBean);
					for(int i =0;i<detailBean.getLadders().size();i++) {
						WaterPriceLadderBean ladderBean = detailBean.getLadders().get(i);
						mapper.insertWaterPriceLadder(ladderBean);
					}
				}
			}
			MessageBean<WaterPriceBean> ret = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", WaterPriceBean.class);
			ret.setData(bean);
			return ret;
		} catch (Exception e) {
			factory.close(false);
			logger.error("非法参数", e);
			return MessageBean.create(Constant.ILLEGAL_PARAMETER, "非法参数", void.class);
		}
	}
}